import SparkMD5 from 'spark-md5';

self.onmessage = async function (e){
  const { file, start, end, CHUNK_SIZE } = e.data;
  const result = [];
  for (let i = start; i < end; i++) {
    const prom = createChunk(file, i, CHUNK_SIZE)
    result.push(prom);
  }
  const chunks = await Promise.all(result)
  self.postMessage(chunks)
};

function createChunk(file, index,chunkSize) {
  return new Promise((resolve, reject) => {
    const start = index * chunkSize;
    const end = start + chunkSize;
    const spark = new SparkMD5.ArrayBuffer();
    const fileReader = new FileReader();
    const blob = file.slice(start, end);

    fileReader.onload = (e) => {
      if (!e.target || !e.target.result) return;

      spark.append(e.target.result);
      resolve({
        start,
        end,
        index,
        blob,
        hash: spark.end(),
      });
    };
    fileReader.readAsArrayBuffer(blob);
  })
}



